#include "image_pixformat_convertor.h"


using namespace sensor::camera;

ImagePixFormatConvertor::ImagePixFormatConvertor(int, int) {
//    cudaMalloc((void**)&gpu_buff_UYVY, width * height * 2);
//    cudaMalloc((void**)&gpu_buff_GBR, width * height * 3);
}

ImagePixFormatConvertor::~ImagePixFormatConvertor() {
//    cudaFree(gpu_buff_UYVY);
//    cudaFree(gpu_buff_GBR);
}

cv::Mat ImagePixFormatConvertor::convert_uyvy422_to_bgr_by_opencv(const void* pyuv, int width, int height)
{
    const cv::Size imgsz(width, height);

    cv::Mat yuv(imgsz, CV_8UC2, (void*)pyuv);
    cv::Mat bgr;
    cv::cvtColor(yuv, bgr, cv::COLOR_YUV2BGR_UYVY);

    return bgr;
}

#if 0
cv::Mat ImagePixFormatConvertor::convert_uyvy422_to_bgr_by_cuda(const void* pyuv, int width, int height)
{
    const cv::Size imgsz(width, height);

    cv::Mat bgr(imgsz, CV_8UC3);
    cv::Mat rgb(imgsz, CV_8UC3);

    cudaMemcpy((void*)gpu_buff_UYVY, (const void*)pyuv, width * height * 2, cudaMemcpyHostToDevice);

    NppiSize roi = { width, height };
    nppiYCbCr422ToBGR_8u_C2C3R(gpu_buff_UYVY, width * 2, gpu_buff_GBR, width * 3, roi);

    cudaMemcpy((void*)rgb.data, (const void*)gpu_buff_GBR, width * height * 3, cudaMemcpyDeviceToHost);

    cv::cvtColor(rgb, bgr, cv::COLOR_RGB2BGR);
    return bgr;
}
#endif

cv::Mat ImagePixFormatConvertor::convert_uyvy422_to_rgb_by_opencv(const void* pyuv, int width, int height)
{
    const cv::Size imgsz(width, height);

    cv::Mat yuv(imgsz, CV_8UC2, (void*)pyuv);
    cv::Mat rgb(imgsz, CV_8UC3);
    cv::cvtColor(yuv, rgb, cv::COLOR_YUV2RGB_UYVY);

    return rgb;
}

#if 0
cv::Mat ImagePixFormatConvertor::convert_uyvy422_to_rgb_by_cuda(const void* pyuv, int width, int height)
{
    const cv::Size imgsz(width, height);

    cv::Mat rgb(imgsz, CV_8UC3);

    cudaMemcpy((void*)gpu_buff_UYVY, (const void*)pyuv, width * height * 2, cudaMemcpyHostToDevice);

    NppiSize roi = { width, height };
    nppiYCbCr422ToBGR_8u_C2C3R(gpu_buff_UYVY, width * 2, gpu_buff_GBR, width * 3, roi);

    cudaMemcpy((void*)rgb.data, (const void*)gpu_buff_GBR, width * height * 3, cudaMemcpyDeviceToHost);

    return rgb;
}
#endif
